


//#include "iotv30_config.h"
#include  "rtc_calendar.h"

#include "platform.h"
#include "cm_time.h"
#include "cm_sys.h"
#include "cm_fs.h"

#include "logfile.h"
#include "user_flash.h"



#define   LOG_FILE_FLASH_ADDR    (0U)

const char *file_name[LOG_FILE_NUM] = {
    "logfile0",
    "logfile1",
    "logfile2",
    "logfile3"};//不允许修改

typedef struct
{
    int32_t id;         // 0,1,2,3
    uint32_t total_cnt; // 从1开始往上递增，用于判断哪个文件更新（此文件系统无法获取文件修改时间）
} log_file_t;

log_file_t log_file = {
    .id = 0,
    .total_cnt = 0,
};

/**
 * @brief 获取日志文件名称
 * 
 * @param seq 顺序，0表示最新，1表示次新，依次类推
 * @return char* 
 */
const char* logfile_get_name(int8_t seq)
{
    int8_t final=log_file.id - seq;
    if(final < 0)final += LOG_FILE_NUM;
    if(final < 0 || final >= LOG_FILE_NUM)final=0;
    return file_name[final];
}


 // logfile_create_new(log_file.id,log_file.total_cnt);

static void logfile_create_new(int id, int total_cnt)
{
  FILE * pFile = NULL;

    logout( "%s\n",__FUNCTION__);

    pFile = File_Unlock( file_name[id] ) ;

  //文件操作
	if (  NULL == pFile)
	{// //打开失败---文件不存在
		logout( "%s fail! open file %s fail!\n",__FUNCTION__,file_name[id] );

	}else{

        char buf[64];
        uint32_t len = snprintf(buf, sizeof(buf),"file %d\n",total_cnt);
        // cm_fs_write(fd, buf, len);
        // cm_fs_close(fd);

        WriteDataToFlash_8Bits(pFile, (uint8_t*)buf,LOG_FILE_FLASH_ADDR,len );  	

        File_Lock( pFile);

	}	

}


static void logfile_init(void)
{
    int count = 0, found = 0;
    for (uint8_t i = 0; i < LOG_FILE_NUM; i++)
    {
        if (!cm_fs_exist(file_name[i]))
        {
            continue;
        }
        
        cm_log_printf(0,"file %d existed\n",i);
        int32_t fd = cm_fs_open(file_name[i], CM_FS_RB);
        if (fd >= 0)
        {
            char buf[64] = {0};
            cm_fs_seek(fd, 0, CM_FS_SEEK_SET);
            cm_fs_read(fd, buf, 20);
            if ( sscanf(buf, "file %d", &count) == 1 ) 
            {
                cm_log_printf(0,"cnt %d\n",count);
                if (count > log_file.total_cnt)
                {
                    log_file.total_cnt = count;
                    log_file.id = i;
                    found = 1;
                }
            }
            cm_fs_close(fd);
        }
    }

    if (!found) // 没有任何日志文件存在
    {
        cm_log_printf(0,"No log file found, create new file\n");
        log_file.id = 0;
        log_file.total_cnt = 1;
        logfile_create_new(log_file.id,log_file.total_cnt);
    }
}






/**
 * @brief 无需添加换行，内部添加了换行
 * 
 * @param add_stamp 
 * @param format 
 * @param ... 
 */
void logfile_write(uint8_t add_stamp, const char *format, ...)
{
    if(!log_file.total_cnt)
    {
        logfile_init();
    }

    /*准备写入内容*/
    char log_buf[256 + 1];
    uint16_t len = 0;

    if (add_stamp)
    {
/*-----------------
        cm_tm_t t;
        cm_sec_to_date((uint32_t)(cm_rtc_get_current_time() + cm_rtc_get_timezone() * 60 * 60), &t);

        if (t.tm_year < 2024)
        { // rtc invalid
            len += snprintf(&log_buf[len], sizeof(log_buf) - len, "[  rtc invalid  ] ");
        }
        else
        {
            len += snprintf(&log_buf[len], sizeof(log_buf) - len, "%02ld-%02ld-%02ld %02ld:%02ld:%02ld ",
                            t.tm_year - 2000, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec);
        }
    }

----------------*/

        RTC_Data_st rtc_new ;
        RTC_Read( &rtc_new );



        if (rtc_new.ucYear < 24)
        { // rtc invalid
            len += snprintf(&log_buf[len], sizeof(log_buf) - len, "[  rtc invalid  ] ");
        }
        else
        {
            len += snprintf(&log_buf[len], sizeof(log_buf) - len, "%02hhu-%02hhu-%02hhu %02hhu:%02hhu:%02hhu ",
                            rtc_new.ucYear , rtc_new.ucMonth, rtc_new.ucDate, rtc_new.ucHour, rtc_new.ucMinute, rtc_new.ucSecond);
        }
    }




    va_list args;
    va_start(args, format);
    len += vsnprintf(&log_buf[len], sizeof(log_buf) - len - 5, format, args);
    va_end(args);

    if (len % 2 == 0)
    { // 2字节对齐，很多flash最小写入字节长度为2
        log_buf[len] = ' ';
        len += 1;
    }
    log_buf[len++] = '\n';

    /*写入文件*/
    uint32_t left_size = LOG_FILE_SIZE - cm_fs_filesize(file_name[log_file.id]);
    if (left_size < len || left_size > LOG_FILE_SIZE)
    {
        log_file.id++;
        log_file.id = log_file.id % LOG_FILE_NUM;
        log_file.total_cnt++;
        logfile_create_new(log_file.id,log_file.total_cnt);
        cm_log_printf(0,"last log file full, create new file\n");
    }

    int32_t fd = cm_fs_open(file_name[log_file.id], CM_FS_AB);
    if(fd>=0)
    {
        cm_fs_write(fd, log_buf, len);
        cm_fs_close(fd);
    }
}

/*************************************************************************************************************************/
